package com.simen.downloader;

import android.os.Handler;

import com.simen.downloader.concurrent.WorkPoolExecutor;
import com.simen.downloader.util.Constants;

import java.io.File;
import java.io.FileFilter;
import java.util.LinkedHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhangming on 16/5/11.
 */
public class DownloadCache {

    private final LinkedHashMap<String, ParcelFile> downState =
            new LinkedHashMap<String, ParcelFile>(0, 0.75f, true);
    private File fileDir;
    private long diskFileSize;
    private int diskFileCount;
    final WorkPoolExecutor threadPoolExecutor = new WorkPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new
            LinkedBlockingQueue<Runnable>());
    private Handler handler;

    public DownloadCache(String fileDir, long diskFileSize, int diskFileCount) {
        this.diskFileSize = diskFileSize;
        this.diskFileCount = diskFileCount;
        init(fileDir);
    }

    void init(String fileDir) {
        File dir = new File(fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
            return;
        }

        if (handler == null) {
            handler = new Handler();
        }

        threadPoolExecutor.execute(new LoadLocal(handler, fileDir, downState));
    }

    ParcelFile getWork(String fileUrl) {
        return downState.get(fileUrl);
    }

    void setStatus(ParcelFile status) {
        String fileUrl = status.getFileUrl();
        ParcelFile storageFile = downState.get(fileUrl);
        if (storageFile != null && !storageFile.isCleared()) {
            downState.put(fileUrl, status);
        }
    }

    void setStatus(String fileUrl, ParcelFile status) {
        downState.put(fileUrl, status);
    }

    private static class LoadLocal implements Runnable {

        final LinkedHashMap<String, ParcelFile> downState;
        final Handler handler;
        final String dirPath;

        public LoadLocal(Handler handler, String dirPath, LinkedHashMap<String, ParcelFile> downState) {
            this.handler = handler;
            this.downState = downState;
            this.dirPath = dirPath;
        }

        @Override
        public void run() {
            File dir = new File(dirPath);
            File[] allfile = dir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    if (!pathname.getPath().endsWith(Constants.LOGEXT)) {
                        return false;
                    }
                    return true;
                }
            });

            if (allfile == null || allfile.length == 0) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        downState.clear();
                    }
                });
                return;
            }

            final LinkedHashMap<String, ParcelFile> cacheState = new LinkedHashMap<String, ParcelFile>(0, 0.75f, true);
            for (int index = 0; index < allfile.length; index++) {
                StorageFile storageFile = (StorageFile) DownloadHelper.getFileWriter(allfile[index]);
                if (storageFile != null) {
                    cacheState.put(storageFile.getFileUrl(), new ParcelFile(storageFile));
                }
            }
            if (!cacheState.isEmpty()) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        downState.putAll(cacheState);
                    }
                }, 0);
            }
        }
    }
}
